using System;
using System.Messaging;

namespace ScottLane.VideoInbox
{
    /// <summary>
    /// A wrapper for the notification message queue that is used to send messages from the
    /// background services to Media Center.
    /// </summary>
    public class NotificationQueue
    {
        private readonly string queuePath = @".\Private$\Video Inbox Notifications";
        private MessageQueue queue;

        /// <summary>
        /// Initializes a new instance of the NotificationQueue class.
        /// </summary>
        public NotificationQueue()
        {
            if (MessageQueue.Exists(queuePath))
            {
                queue = new MessageQueue(queuePath);
            }
            else
            {
                queue = MessageQueue.Create(queuePath, false);
            }
        }
        
        /// <summary>
        /// Adds a notification to the back of the queue.
        /// </summary>
        /// <param name="notification">The notification.</param>
        public void Add(Notification notification)
        {
            queue.Send(notification);
        }

        /// <summary>
        /// Removes a notification from the front of the queue.
        /// </summary>
        /// <returns>The notification.</returns>
        public Notification Remove()
        {
            Notification notification = Peek();

            if (notification != null)
            {
                Message message = queue.Receive(TimeSpan.Zero);
                notification = (Notification)message.Body;
            }

            return notification;
        }

        /// <summary>
        /// Peeks at the message at the front of the queue without removing it.
        /// </summary>
        /// <returns>The notification.</returns>
        public Notification Peek()
        {
            Notification notification = null;
            Message message = queue.Peek(TimeSpan.Zero);

            if (message != null)
            {
                notification = (Notification)message.Body;
            }

            return notification;
        }
    }
}
